import { generateDataInterface } from '@/types/modules/editor/server/code-transformer/utils/export/generateTsType';
import { ITypeEntity } from '@/types/modules/superType/types';
import { apiTypeEntityToCode } from './apiTypeParser';

/**
 * 生成云函数代码，在顶部添加 JSDoc 元数据注释
 */
function generateCloudFunctionCode(typeEntity: ITypeEntity): string {
  const source = typeEntity.source || '';

  // 检查代码顶部是否已经有 JSDoc 注释
  const hasExistingJSDoc = source.trim().startsWith('/**');

  if (hasExistingJSDoc) {
    // 如果已经有 JSDoc 注释，直接返回原代码
    return source;
  }

  // 生成 JSDoc 元数据注释
  const metaComment = generateCloudFunctionMetaComment(typeEntity);

  // 在代码顶部添加注释
  return `${metaComment}
${source}`;
}

/**
 * 生成云函数的 JSDoc 元数据注释
 */
function generateCloudFunctionMetaComment(typeEntity: ITypeEntity): string {
  const lines = [`/**`];

  // 主描述
  if (typeEntity.desc) {
    lines.push(` * ${typeEntity.desc}`);
  }

  // 详细介绍
  if (typeEntity.intro) {
    lines.push(` * ${typeEntity.intro}`);
  }

  // 只有当有描述时，才在描述和方法信息之间添加空行分隔
  const hasDescription = typeEntity.desc || typeEntity.intro;
  const methods = typeEntity.data?.methods;
  const hasMethods = Array.isArray(methods) && methods.length > 0;

  if (hasDescription && hasMethods) {
    lines.push(` *`);
  }

  // HTTP 方法支持
  if (hasMethods && Array.isArray(methods)) {
    const methodsStr = methods.join(', ');
    lines.push(` * @methods ${methodsStr}`);
  }

  lines.push(` */`);
  return lines.join('\n');
}

export const getTypeFileCode = async function (typeEntity: ITypeEntity) {
  switch (typeEntity?.type) {
    case 'cloud_function':
      return generateCloudFunctionCode(typeEntity);
    case 'vo':
      return generateDataInterface(typeEntity, {
        isFileCode: true,
        hasDefaultValue: true,
        isDbMode: true,
      });
    case 'data':
      return generateDataInterface(typeEntity, {
        isFileCode: true,
        hasDefaultValue: true,
        isDbMode: true,
      });
    case 'dto':
      return typeEntity.source;
    case 'api':
      return apiTypeEntityToCode(typeEntity);
    case 'code':
      return typeEntity.source;
    case 'action':
      return typeEntity.source || typeEntity.code?.value || '';
    case 'draw':
      return typeEntity.source;
    case 'flow':
      return typeEntity.source;
    case 'api-import':
      return JSON.stringify({
        host: typeEntity.host,
        hostConstantName: typeEntity.hostConstantName,
        desc: typeEntity.desc,
        apiDocStr: typeEntity.apiDocStr ? JSON.parse(typeEntity.apiDocStr) : undefined,
      }, undefined, 2);
    default:
      if (typeEntity.language && typeEntity.source) {
        return typeEntity.source;
      }
      return undefined;
  }
};
